package com.power.algorithm.structure.linked.single;

/**
 * @description:
 * @author: jiangnan
 * @time: 2021/5/19 11:42 上午
 * <p>
 * 单链表的增删查改
 * 单链表需要一个头指针
 * 单链表需要一个头标志位
 * 单链表需要记录一下长度
 * 单链表需要一个尾标志位
 */
public class SingleLinkedList<E> {

    public Node<E> head;
    private int size = 0;

    public Node<E> tail;

    static class Node<E> {
        Node next;
        E value;

        public Node(Node next, E value) {
            this.value = value;
            this.next = next;
        }

        public Node(E value) {
            this.value = value;
        }
    }


    public SingleLinkedList() {

    }

    public void add(E value) {
        Node newNode = new Node(value);
        //如果头节点没有被初始化
        if (head == null) {
            head = newNode;
            size++;
            return;
        }
        //如果被初始化，则遍历所有的节点
        Node tmp = head;
        while (tmp.next != null) {
            tmp = tmp.next;
        }
        tmp.next = newNode;
        size++;
    }

    public void remove(E element) {

        Node tmp = head;
        while (tmp.next != null) {

            if (tmp.value == element) {
                tmp.next = tmp.next.next;
                size--;
                return;
            }
            tmp = tmp.next;
        }

    }

    public Object get(E element) {
        if (head == null) {
            return "未找到元素";
        }
        int location = 1;
        Node tmp = head;
        while (tmp.next != null) {
            if (tmp.value.equals(element)) {
                return location;
            }
            tmp = tmp.next;
            location++;
        }

        return "未找到元素";
    }

    public boolean isExists(E element) {
        Node tmp = head;
        while (tmp.next != null) {

            if (tmp.value == element) {
                return true;
            }
            tmp = tmp.next;
        }
        return false;
    }

    public static void main(String[] args) {
        SingleLinkedList<Integer> singleLinkedList = new SingleLinkedList<Integer>();
        //----------------添加元素------------------
        singleLinkedList.add(1);
        singleLinkedList.add(2);
        singleLinkedList.add(3);
        //----------------查找元素------------------
        System.out.println(singleLinkedList.get(33));
        System.out.println(singleLinkedList.size);
        //----------------删除元素------------------
        System.out.println("=============删除============");
        singleLinkedList.remove(2);
        System.out.println(singleLinkedList.size);
        //----------------是否存在元素------------------
        System.out.println("=============isExists============");
        System.out.println(singleLinkedList.isExists(1));
    }
}
